package cn.xawl.interview.thread;

import java.util.concurrent.*;

/**
 * @author lh
 * @date 2020/08/26 16:15:18
 **/
public class SemaphoreDemo {

    public static void main(String[] args) {
        //构造器变量为一个通行证，只有线程获取到通行证后才可以执行操作
        Semaphore semaphore = new Semaphore(10);//模拟10张票（10张通行证）

        ExecutorService pool = new ThreadPoolExecutor(5, 10, 1L, TimeUnit.SECONDS, new SynchronousQueue<>(), new ThreadPoolExecutor.AbortPolicy());
        for (int i = 1; i <= 20; i++) {//模拟有20人来抢票
            new Thread(() -> {
                try {
                    semaphore.acquire();//从信号量中获取通行证，如果没有就会阻塞，直到线程中断
                    System.out.println(Thread.currentThread().getName() + "\t抢到票，剩余：" + semaphore.availablePermits());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                    System.out.println(Thread.currentThread().getName() + "\t退票");
                }
            }, String.valueOf(i)).start();
        }
//        System.out.println(semaphore.getQueueLength() + "位用户没有抢到票：");

    }

}
